package com.briup.security;

import com.briup.security.util.ImageCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

public class ImageCodeFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(ImageCodeFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        ServletOutputStream outputStream = response.getOutputStream();
        try {
            // 如果是登录请求则放行
            if (request.getRequestURI().equals("/user/login") && "post".equalsIgnoreCase(request.getMethod())) {
                // 获取校验码
                String code = request.getParameter("code");
                HttpSession session = request.getSession();
                ImageCode imageCode = (ImageCode) session.getAttribute("SESSION_IMAGE_CODE");
                if (code == null || "".equals(code)) {
                    outputStream.write("验证码为空".getBytes());
                    return;
                }

                if (imageCode == null || imageCode.getExpireTime().isBefore(LocalDateTime.now())) {
                    outputStream.write("验证码已过期".getBytes());
                    return;
                }

                if (!imageCode.getCode().equalsIgnoreCase(code)) {
                    outputStream.write("验证码不匹配".getBytes());
                    return;
                }

                session.removeAttribute("SESSION_IMAGE_CODE");
            }
            filterChain.doFilter(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }
}
